'use client'
import React, {useEffect, useRef, useState} from "react";
import {  publishServer, userServer, reportServer, collectServer,  rocketServer} from '@/api';
import { PublishItem, publishPageParams } from '@/api/api'
import { showTagsByRole } from '@/utils/index'
import { useStore } from '@/store';
import { getLocalStorage } from '@/utils/localStorage'
import { toast } from "react-toastify";
import Title from "@/components/title"
import Content from "@/components/content"
import Carman from "@/components/carman"
import Search from "@/components/search"
import sytles from "./index.module.scss"
import Modal from 'react-modal';
import ReportForm from "@/components/ReportForm";
import ShowNumber from "@/components/ShowNumber";


const defaultAction : Array<{value: 'rocket' | 'collect' | 'report', name: string}>= [
  {
    value: 'rocket',
    name: '助力'
  },
  {
    value: 'collect',
    name: '收藏'
  },
  {
    value: 'report',
    name: '举报'
  }
]


const HighlightedText : React.FC<{text: string, highlight: string}>= ({ text, highlight }) => {
  // 使用正则表达式在文本中匹配关键词
  const parts = text.split(new RegExp(`(${highlight})`, 'gi'));
  return (
    <span>
      {parts.map((part, index) =>
        part.toLowerCase() === highlight.toLowerCase() ? (
          // 高亮部分
          <span key={index} style={{ color: '#ff9632', fontWeight: 'bold' }}>
            {part}
          </span>
        ) : (
          // 普通部分
          <span key={index}>{part}</span>
        )
      )}
    </span>
  );
};


export default function Car(){
  const [pageInfo, setPageInfo] = useState<publishPageParams>({
    pageNumber: 1,
    pageSize: 10,
    search:'',
    map: {pro: {code: '00', name: '全国'}},
    role:'driver',
    des:'all'
  });
  const [list, setList] = useState<Array<PublishItem>>([]);
  const [total, setTotal] = useState<Number>(0);
  const [publishId, setPublishId] = useState<string | null>(null);


  const [modalIsOpen, setIsOpen] = React.useState(false);
  function openModal() {
    setIsOpen(true);
  }
  function closeModal() {
    setIsOpen(false);
  }
  const customStyles = {
    content: {
      top: '0',
      left: '0',
      right: '0',
      bottom: '0',
      // marginRight: '-50%',
      // transform: 'translate(-50%, -50%)',
      background:'rgba(0,0,0,.5)'
    },
  };


  const userInfo = useStore((state:any) => state.userInfo);
  const access_token = useStore((state:any) => state.access_token);



  const [showNumberVisible, setShowNumberVisible] = useState<boolean>(false);
  const [showNumberInfo, setShowNumberInfo] = useState({});

  console.log('userInfo---car', userInfo, access_token);

  const getQueryParams = ({map, search, des}:any) => {
    setPageInfo({
      ...pageInfo,
      map,
      search,
      des
    })
  }


  // 请求列表
  const queryPage = async () => {
    try {
      const {code, data, message } = await publishServer.publishPage({...pageInfo});
      if(code === 200){
        setList(data.list)
        setTotal(data.total)
        console.log('列表数据', data)
      } else {
        toast.warn(message)
      }
    } catch (error) {
      console.log(error)
    }
  };
  useEffect(() => {
    queryPage();
  }, [pageInfo, pageInfo.pageSize])


  const loadMore = () => {
    setPageInfo({
      ...pageInfo,
      pageSize: pageInfo.pageSize + 10
    })
  }

  
  // 获取省市区起点和省区市终点
  type QueryStartLocalOrEndLocal = (type: 'start' | 'end', item: PublishItem) => string | React.ReactElement | React.ReactNode
  const queryStartLocalOrEndLocal : QueryStartLocalOrEndLocal= (type, item) => {
    // const startKeys = ['startProvince', 'startCity', 'startCounty'];
    // const endKyes = ['endProvince', 'endCity', 'endCounty'];
    const search = (t: 'start' | 'end', item: PublishItem) => {
      let arr = [];
      for(let [key, value] of Object.entries(item)){
        if(key === `${t}Province`){
          value?.name && arr.push(value.name)
        }
        if(key === `${t}City`){
          value?.name &&arr.push(value.name)
        }
        if(key === `${t}County`){
          value?.name && arr.push(value.name)
        }
      }
      return arr;
    };
    let list = search(type, item);
    return (list.length > 2 ? list.slice(1) : list).join("/");
  }


  type ClickHandle = (params: {publish_id: string, type: 'rocket' | 'collect' | 'report'}) => void
  const clickHandle: ClickHandle =async  ({type, publish_id}) => {
    const _USER : string | null= getLocalStorage('userInfo')
    const userDetail = _USER ? JSON.parse(_USER) : {};
    console.log('type',userDetail, type, publish_id)
    if(!userDetail?.id){
      console.log('用户id不存在')
      alert("请您先注册或登录")
      return;
    }
    const hasRes = await userServer.beforeHaveThisBehavior({type, publish_id, userId: userDetail.id});
    if( hasRes.code === 1000){
      let { name } = defaultAction.find(t => t.value === type) || {};
      alert(`您已经${name}过了` || hasRes.message)
      return;
    }
    try {
      const data = await publishServer.userOperateBehavior({
        publish_id: `${publish_id}`,
        data: {
          type: type,
          userId: userDetail.id
        }
      });
      if(data.code === 200){
           // 如果是举报那么需要在另外一个弹窗点击确定之后才能操作
        if(type === 'report'){
          setPublishId(publish_id);
          openModal();
          return;
        }

        if(type === "collect"){
          const collectRes = await collectServer.createCollectItem({
            userId: userDetail.id,
            publish_id: publish_id
          });
          if(collectRes.code !== 200){
              alert('收藏失败')
              return;
          }
        }
        if(type === "rocket"){
          const rocketRes = await rocketServer.createRocketItem({
            userId: userDetail.id,
            publish_id: publish_id
          })
          if(rocketRes.code !== 200){
            alert('助力失败')
            return;
          }
        }
        queryPage()
      }
      console.log('data', data)
    } catch (error) {
      console.log(error)
    }
  }


  const getFormData = async (formData: any) => {
    try {
      const _USER : string | null= getLocalStorage('userInfo')
      const userDetail = _USER ? JSON.parse(_USER) : {};
      if(!publishId && !userDetail?.id){
        closeModal();
        alert('缺少用户id和发布id')
        return
      }
      const params = {
        reportContent: formData.des,
        reportType: formData.type,
        publish_id: publishId as string,
        userId: userDetail.id
      }
      const reportData = await reportServer.createReportItem(params);
      if(reportData.code === 200){
        queryPage();
        setPublishId(null);
      }
      closeModal();
    } catch (error) {
      console.log(error)
    }
  }

const showContactInfo = (type: 'wechat' | 'phone', {phone, wechat}:any) => {
  const _USER : string | null= getLocalStorage('userInfo')
  const userDetail = _USER ? JSON.parse(_USER) : {};
  if(!userDetail?.id){
    console.log('用户id不存在')
    alert("请您先注册或登录")
    return;
  }
  setShowNumberVisible(true)
  if(type === "wechat"){
    setShowNumberInfo({
      wechat: wechat
    })
  } 
  if(type === "phone"){
    setShowNumberInfo({
      phone:phone
    })
  }

}
  return <Content>
    <div className={`${sytles["car-coomponent"]}`}>
      <Search getQueryParams={getQueryParams}/>
      <div className={`${sytles["car-list"]}`}>
        <Modal
          isOpen={modalIsOpen}
          onRequestClose={closeModal}
          style={customStyles}
          // appElement={document.querySelector('body')}
        >
          <ReportForm getFormData={getFormData} onClose={closeModal}/>
        </Modal>


        <Modal
           isOpen={showNumberVisible}
           onRequestClose={() => setShowNumberVisible(false)}
           style={customStyles}
        >
          <ShowNumber onClose={() => setShowNumberVisible(false)} {...showNumberInfo} />
        </Modal>

        <Title icon="fa-car" title="以下车辆正在寻找乘客"/>
        {
          list.map((item, i) => <Carman 
              key={item.id}
              startPoint={ <HighlightedText text={item.startLocation}  highlight={pageInfo.search} />} 
              endPoint={ <HighlightedText text={item.endLocation}  highlight={pageInfo.search} />}
              tags={showTagsByRole(item)}
              id="123"
              actives={[{icon:"fa-regular fa-star", txt:"收藏", num:item.collect ? Number(item.collect) : 0, clickHandle: () => clickHandle({type:'collect', publish_id: `${item.id}`})}, {icon:"fa-regular fa-bell", txt:"举报", num:item.report ? Number(item.report) : 0, clickHandle: () => clickHandle({type:'report', publish_id: `${item.id}`})}, {icon:"fa-light fa-rocket", txt:"助力", num: item.rocket ? Number(item.rocket) : 0, clickHandle: () => clickHandle({type:'rocket', publish_id: `${item.id}`})}]}
              btns={[{icon:"fa-brands fa-weixin", txt:"获取微信", clickHandle: () => showContactInfo('wechat', item) }, {icon:"fa-solid fa-phone", txt:"获取手机号",  clickHandle: () => showContactInfo('phone', item)}]}
              remarks={item.remarks}
              userInfo={{nickname: item.nickname, created_at: item.created_at}}
              endLocal={queryStartLocalOrEndLocal('end', item)}
              startLocal={queryStartLocalOrEndLocal('start', item)}
            />)
        }

        <div className={`${sytles["loadMore"]}`} 
          onClick={ () => Number(pageInfo?.pageSize) >= Number(total) ? void(0): loadMore()} >
            {
              `${
                Number(pageInfo?.pageSize) >= Number(total) ? '没有更多了' : '点击加载更多'
              }`
            }
        </div>
      </div>
    </div>
  </Content>
}